package com.example.demo.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by gf on 2018/10/17.
 */
@Aspect
@Component
public class LoginAspect {

    long startTime;
    long endTime;

    private static Logger logger = LoggerFactory.getLogger(LoginAspect.class);

    @Pointcut("execution(public * com.example.demo.controller.StudentController.*(..))")
    private void point(){
    }

    @Before("point()")//参数为方法名
    public void doBefore(JoinPoint joinPoint){
        startTime = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        logger.info("url={}",request.getRequestURL());
        //ip
        logger.info("ip={}",request.getRemoteAddr());
        //method
        logger.info("method={}",request.getMethod());
        //class_method
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+
                    joinPoint.getSignature().getName());
        //arg
        logger.info("arg={}",joinPoint.getArgs());
    }

    @After("point()")
    public void doAfter(){
        endTime = System.currentTimeMillis();
        float var = (float) ((endTime - startTime) / 1000.0);
        logger.info("方法执行完毕使用了"+ var +"ms");
    }

    @AfterReturning(returning = "object",pointcut = "point()")
    public void doAfterReturning(Object object){
        logger.info(object.toString());
    }

}
